package com.zdltech.lightappupdatelib.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.zdltech.lightappupdatelib.entity.AppVertionEntity;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

/**
 *
 * 轻量APP更新工具
 */

public class LightAppUpdateUtils {


    public static  String rootFile;//存储文件根目录
    public static final String IGNORE_VERSION = "ignore_version";
    private static final String PREFS_FILE = "light_update_config.xml";

    public static boolean isWifi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        return info != null && info.getType() == ConnectivityManager.TYPE_WIFI;
    }


    /**
     * 获取app的文件的路径
     * @param updateAppBean
     * @return
     * @throws Exception
     */
    public static File getAppFile(AppVertionEntity updateAppBean) throws Exception{
        String appName = getApkName(updateAppBean);
        if (rootFile==null){
            throw new Exception("root file is not setting!!! please setting root file example content.getFiles()");
        }
        File rootDir = new File(rootFile.concat(File.separator + updateAppBean.getVersion()).concat(File.separator));
        if (!rootDir.exists()){
            rootDir.mkdirs();
        }
        return new File(rootFile.concat(File.separator + updateAppBean.getVersion()).concat(File.separator + appName));
    }

    /**
     * 获取下载的文件路径
     * @param updateAppBean
     * @return
     */
    public static String getAppFilePath(AppVertionEntity updateAppBean)throws Exception{
        if (rootFile==null){
            throw new Exception("root file is not setting!!! please setting root file example content.getFiles()");
        }
        File rootDir = new File(rootFile.concat(File.separator + updateAppBean.getVersion()).concat(File.separator));
        if (!rootDir.exists()){
            rootDir.mkdirs();
        }
        return rootDir.getAbsolutePath();
    }

    /**
     * 获取APK的名字
     * @param updateAppBean
     * @return
     */
    @NonNull
    public static String getApkName(AppVertionEntity updateAppBean) {
        String tempName = updateAppBean.getUpdateUrl()+updateAppBean.getVersion();
        String appName = Md5Util.getMD5Str(tempName).concat(".apk");
        return appName;
    }

    public static boolean appIsDownloaded(AppVertionEntity updateAppBean) throws Exception{
        //md5不为空
        //文件存在
        //md5只一样
        File appFile = getAppFile(updateAppBean);
        return !TextUtils.isEmpty(updateAppBean.getFileMd5())
                && appFile.exists()
                && Md5Util.getFileMD5(appFile).equalsIgnoreCase(updateAppBean.getFileMd5());
    }

    public static boolean installApp(Context context, File appFile) {
        try {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri fileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileProvider", appFile);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
            }
            if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                context.startActivity(intent);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static Intent getInstallAppIntent(Context context, File appFile) {
        try {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri fileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileProvider", appFile);
                intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
            }
            return intent;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getVersionName(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        if (packageInfo != null) {
            return packageInfo.versionName;
        }
        return "";
    }

    public static int getVersionCode(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        if (packageInfo != null) {
            return packageInfo.versionCode;
        }
        return 0;
    }

    public static PackageInfo getPackageInfo(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前的包名
     * @param context
     * @return
     */
    public static String getPackageName(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        if (packageInfo != null) {
            return packageInfo.applicationInfo.packageName;
        }
        return "";
    }

    /**
     * 获取APK是否在前台运行
     * @param context
     * @return
     */
    public static boolean isAppOnForeground(Context context) {

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {

            if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    public static String getAppName(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        if (packageInfo != null) {
            return packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
        }
        return "";
    }

    public static Drawable getAppIcon(Context context) {
        try {
            return context.getPackageManager().getApplicationIcon(context.getPackageName());
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {


        Bitmap bitmap = Bitmap.createBitmap(

                drawable.getIntrinsicWidth(),

                drawable.getIntrinsicHeight(),

                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

                        : Bitmap.Config.RGB_565);

        Canvas canvas = new Canvas(bitmap);

        //canvas.setBitmap(bitmap);

        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

        drawable.draw(canvas);

        return bitmap;

    }

    public static int dip2px(int dip, Context context) {
        return (int) (dip * getDensity(context) + 0.5f);
    }

    public static float getDensity(Context context) {
        return getDisplayMetrics(context).density;
    }

    public static DisplayMetrics getDisplayMetrics(Context context) {
        return context.getResources().getDisplayMetrics();
    }


    /**
     * 获取Manifest 下面 META-DATA的值
     * @param context
     * @param name
     * @return
     */
    public static String getManifestString(Context context, String name) {
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return appInfo.metaData.getString(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static SharedPreferences getSP(Context context) {
        return context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
    }

    /**
     * 保存忽略的版本号
     * @param context
     * @param newVersion
     */
    public static void saveIgnoreVersion(Context context, String newVersion) {
        getSP(context).edit().putString(IGNORE_VERSION, newVersion).apply();
    }

    /**
     * 获取 忽略的版本号
     * @param context
     * @return
     */
    public static String getIgnoreVersion(Context context) {
       return getSP(context).getString(IGNORE_VERSION, "");
    }

    /**
     * 是否需要忽略
     * @param context
     * @param newVersion
     * @return
     */
    public static boolean isNeedIgnore(Context context, String newVersion) {
        return getSP(context).getString(IGNORE_VERSION, "").equals(newVersion);
    }

    /**
     * 字节到MB转换
     * @param size
     * @return
     */
    public static String fileSizeByMB(long size){
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    public static void main(String[] args){
        System.out.println("Math.log10(1024)="+Math.log10(1024));
    }
}
